<?php
namespace app\Backend\controller;;
use think\Db;
use clt\Leftnav;
use app\Backend\model\Admin;
use app\Backend\model\AuthGroup;
use app\common\model\AuthRule;
use think\Validate;
class Auth extends Common
{
    //管理员列表
    public function adminList(){
        $val=input('val');
        $url['val'] = $val;
        $this->assign('testval',$val);
        $map='';
        if($val){
            $map['a.username|a.email|a.tel']= array('like',"%".$val."%");
        }

        $list=Db::table(config('database.prefix').'admin')->alias('a')
            ->join(config('database.prefix').'auth_group ag','a.group_id = ag.group_id','left')
            ->field('a.*,ag.title')
            ->where($map)
            ->select();
        $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        $this->assign('lists',$result['data']);
        return view();
    }

    //添加管理员
    public function adminAdd(){
        if(request()->isPost()){
            $data = input('post.');
            $check_user = Admin::get(['username'=>$data['username']]);

            if ($check_user) {
                return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
            }
            $data['pwd'] = input('post.pwd', '', 'md5');
            $data['add_time'] = time();
            $data['ip'] = request()->ip();
            //验证
            $msg = $this->validate($data,'app\Backend\validate\Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            //单独验证密码
            $checkPwd = Validate::is(input('post.pwd'),'require');
            if (false === $checkPwd) {
                return $result = ['code'=>0,'msg'=>'密码不能为空！'];
            }
            if(!empty($data['email']) && !is_email($data['email'])){
                return $result = ['code'=>0,'msg'=>'输入邮箱格式不对'];
            }
            //添加
            if (Admin::create($data)) {
                return ['code'=>1,'msg'=>'管理员添加成功!','url'=>'/reload'];
            } else {
                return ['code'=>0,'msg'=>'管理员添加失败!'];
            }
        }else{
            $auth_group=db('auth_group')->select();
            $this->assign('authGroup',$auth_group);
            $this->assign('title',lang('add').lang('admin'));
            $this->assign('info','null');
            $this->assign('selected', 'null');
            return view('adminForm');
        }
    }

    //删除管理员
    public function adminDel(){
        $admin_id=input('admin_id');
        $map['admin_id'] = $admin_id;
        $map['is_sys'] = 0; //0=>不是系统管理员，可删除!
        if (db('admin')->where($map)->delete()){
            return $result = ['code'=>1,'msg'=>'删除成功!','url'=>'/reload'];
        }else{
            return $result = ['code'=>0,'msg'=>'用户信息删除失败!','url'=>''];
        }
    }

    //修改管理员状态
    public function adminState(){
        $id=input('post.id');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = url('adminList');
            exit;
        }
        $status=db('admin')->where('admin_id='.$id)->value('is_open');//判断当前状态情况
        if($status==1){
            $data['is_open'] = 0;
            db('admin')->where('admin_id='.$id)->update($data);
            $result['status'] = 1;
            $result['open'] = 0;
        }else{
            $data['is_open'] = 1;
            db('admin')->where('admin_id='.$id)->update($data);
            $result['status'] = 1;
            $result['open'] = 1;
        }
        return $result;
    }

    //更新管理员信息
    public function adminEdit(){
        if(request()->isPost()){
            $data   = input('post.');
            $pwd    = input('post.pwd');

            $map['admin_id']    = array('neq',input('post.admin_id'));
            $where['admin_id']  = input('post.admin_id');
            if(input('post.username')){
                $map['username'] = input('post.username');
                $check_user = Admin::get($map);
                if ($check_user) {
                    return $result = ['code'=>0,'msg'=>'用户已存在，请重新输入用户名!'];
                }
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','','md5');
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'Admin');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            if(!empty($data['email']) && !is_email($data['email'])){
                return $result = ['code'=>0,'msg'=>'输入邮箱格式不对'];
            }
            Admin::update($data);
            return $result = ['code'=>1,'msg'=>'管理员修改成功!','url'=>'/reload'];
        }else{
            $auth_group=db('auth_group')->select();
            $info = Admin::get(['admin_id'=>input('admin_id')]);
            $this->assign('row', $info);
            $this->assign('authGroup',$auth_group);
            $this->assign('title',lang('edit').lang('admin'));
            return view('adminForm');
        }
    }

    /*-----------------------用户组管理----------------------*/
    //用户组管理
    public function adminGroup(\think\Request $request){
        $AuthGroup = new AuthGroup;
        $map = [];//$request->get();
        $list = $AuthGroup->where($map)->select();
        $this->assign('lists',$list);
        return view();
    }

    //删除管理员分组
    public function groupDel(){
        $map['group_id'] = input('id');
        if ($map['group_id']==1) { //默认1为超级管理员，不可删除！
            return $result = ['code'=>0,'msg'=>'该用户组不可删除!','url'=>''];
        }
        $AuthGroup = new AuthGroup;
        if(AuthGroup::destroy($map)){
             return $result = ['code'=>1,'msg'=>'删除成功!','url'=>'/reload'];
        }
        return $result = ['code'=>0,'msg'=>'信息删除失败!','url'=>''];

    }
    //管理员分组状态:0禁用,1启用
    public function groupState(){
        $map['group_id'] = input('group_id');
        $status = \max(0, (int) input('status') );
        if(db('auth_group')->where($map)->setField(['status'=>$status])){
            return ['code'=>1,'msg'=>'操作成功'];
        }
        return ['code'=>0,'msg'=>'操作失败'];
    }

    //添加管理员分组
    public function groupAdd(){
        if(request()->isPost()){
            $data=input('post.');
            if(empty($data['title'])){
                $this->error("请输入组名称.");
            }
            $data['add_time']= time();
            $data['status'] = 1;
            $data['rules'] = '0,';//不能为空
            AuthGroup::create($data);

            return [
                'code'=> 1,
                'msg' => '用户组添加成功!',
                'url' => '/reload',
            ];
        }else{
            $this->assign('title','添加用户组');
            $this->assign('info','null');
            return $this->fetch('groupForm');
        }
    }

    //修改分组
    public function groupEdit(){
        if(request()->isPost()) {
            $data=input('post.');
            if(empty($data['title'])){
                $this->error("请输入组名称.");
            }
            AuthGroup::update($data);
            $result = ['code'=>1,'msg'=>'用户组修改成功!','url'=>"/reload"];
            return $result;
        }else{
            $id = input('id');
            $info = AuthGroup::get(['group_id'=>$id]);
            $this->assign('row', $info);
            $this->assign('title','编辑用户组');
            return $this->fetch('groupForm');
        }
    }
    //分组配置规则
    public function groupAccess(){
        $nav = new Leftnav();
        $admin_rule=db('auth_rule')->field('id,pid,title')->order('sort asc')->select();
        $rules = db('auth_group')->where('group_id',input('group_id'))->value('rules');
        $arr = $nav->auth($admin_rule,$pid=0,$rules);
        $arr[] = array(
            "id"=>0,
            "pid"=>0,
            "title"=>"全部",
            "open"=>true
        );
        $this->assign('group_id',input('group_id'));
        $this->assign('data',json_encode($arr,true));
        return $this->fetch();
    }
    public function groupSetaccess(){
        $rules = input('post.rules');
        if(empty($rules)){
            return array('msg'=>'请选择权限!','code'=>0);
        }
        $data = input('post.');
        if(AuthGroup::update($data)){
            return array('msg'=>'权限配置成功!','url'=>url('adminGroup'),'code'=>1);
        }else{
            return array('msg'=>'保存错误','code'=>0);
        }
    }

    /********************************权限管理*******************************/
    public function adminRule(){
        if(request()->isPost()){
            $nav = new Leftnav();
            //$arr = cache('authRuleList');
            if(!$arr){
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                //cache('authRuleList', $arr, 3600);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$arr,'rel'=>1];
        }
        $authRule = authRule::all(function($query){
            $query->order('sort', 'asc');
        });

        $nav = new Leftnav();
        $ruleArr = $nav->menu($authRule);
        $this->assign('rules',$ruleArr);
        return view();
    }

    public function ruleAdd(){
        if(request()->isPost()){
            $data = request()->post();

            if(empty($data['title'])){
                return ['code'=>0,'msg'=>"请输入权限名称."];
            }
            $data['menu_status'] = 1;
            $data['addtime'] = time();
            if(authRule::create($data)){
                return $result = ['code'=>1,'msg'=>'权限添加成功!','url'=>"/reload"];
            }
            return ['code'=>0,'msg'=>"数据保存失败."];
        }else{
            $nav = new Leftnav();
            $authRule = authRule::all(function($query){
                $query->order('sort', 'asc');
            });
            $arr = $nav->menu($authRule);
            $this->assign('admin_rule',$arr);//权限列表
            return $this->fetch();
        }
    }
    public function ruleOrder(){
        $auth_rule=db('auth_rule');
        $data['id'] = input('id');
        $data['sort'] = input('val','','intval');
        if($auth_rule->update($data)!==false){
            return $result = ['code'=>1,'msg'=>'','url'=>''];
        }else{
            return $result = ['code'=>0,'msg'=>'排序更新失败!','url'=>''];
        }
    }
    public function ruleState(){
        $id=input('id');
        $status = input('status');
        if(db('auth_rule')->where(array('id'=>$id))->setField(['menu_status'=>$status])){
            return ['code'=>1,'msg'=>''];
        }
        return ['code'=>0,'msg'=>'操作失败'];
    }
    public function ruleTz(){
        $id=input('id');
        $status = input('status');
        if(db('auth_rule')->where(array('id'=>$id))->setField(['authopen'=>$status])){
            return ['code'=>1,'msg'=>''];
        }
        return ['code'=>0,'msg'=>'操作失败'];

    }

    public function ruleDel(){
        if(authRule::destroy(['id'=>input('id')])){
            return $result = ['code'=>1,'msg'=>'删除成功.','url'=>'/reload'];
        }
        return $result = ['code'=>0,'msg'=>'删除失败.','url'=>''];

    }

    public function ruleEdit(){
        $id = input('id');
        if(request()->isPost()) {
           $data = request()->post();
            if(empty($data['title'])){
                return ['code'=>0,'msg'=>"请输入权限名称."];
            }
            if(authRule::update($data)){
                return $result = ['code'=>1,'msg'=>'权限保存成功!','url'=>"/reload"];
            }
            return ['code'=>0,'msg'=>"数据保存失败."];
        }else{
            $admin_rule = authRule::get(function($query){
                $query->where(['id'=>input('id')])->field('id,href,title,icon,sort,menu_status');
            });
            $nav = new Leftnav();
            $authRule = authRule::all(function($query){
                $query->order('sort', 'asc');
            });
            $arr = $nav->menu($authRule);
            $this->assign('admin_rule',$arr);//权限列表
            $row = authRule::get($id);
            $this->assign('row',$row);//权限列表
            return $this->fetch();
        }
    }
}